<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui"/>
  <title>Mojito</title>
  <script src="../js/base.js"></script>
  <link rel="stylesheet" href="../plugins/vant/vant.min.css">
  <link rel="stylesheet" href="../styles/common.css"/>
  <link rel="stylesheet" href="../styles/address-edit.css"/>
</head>
<body>
  <div id="address_edit" class="app">
    <div class="divHead">
      <div class="divTitle">
        <i @click="goBack"><van-icon name="arrow-left" /></i>{{title}}
      </div>
    </div>
    <div class="divContainer">
      <div class="consignee">
        <van-field label="收货人" v-model="form.consignee" placeholder="请填写收货人的姓名" maxlength="15">
          <template #extra>
            <van-radio-group v-model="form.sex" direction="horizontal">
              <van-radio name="1">先生</van-radio>
              <van-radio name="0">女士</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </div>
      <div class="divSplit"></div>
      <div class="phone">
        <van-field label="手机号" v-model="form.phone" type="digit" placeholder="请填写收货手机号码" clearable maxlength="11"/>
      </div>
      <div class="divSplit"></div>
      <div class="area">
        <van-field label="地区" :value="area" placeholder="选择省/市/区" readonly @click="showArea=true"/>
      </div>
      <div class="divSplit"></div>
      <div class="detail">
        <van-field label="门牌号" v-model="form.detail" placeholder="详细地址，街道门牌、楼层房间号等信息" clearable maxlength="200"/>
      </div>
      <div class="divSplit"></div>
      <div class="tag">
        <van-field label="标签">
          <template #input>
            <span v-for="item in tagList" :class="{tagItem:true,[item]:form.tag==item}" @click="checkTag(item)">{{item}}</span>
          </template>
        </van-field>
      </div>
    </div>
    <div class="defaultAddress">
      <van-cell center title="设为默认地址">
        <template #right-icon>
          <van-switch v-model="form.isDefault" size="24" active-color="#ffc200"/>
        </template>
      </van-cell>
    </div>
    <van-button class="btnSave" @click="saveAddress">保存地址</van-button>
    <van-button v-if="id" class="btnDelete" @click="deleteAddress">删除地址</van-button>
    <van-popup v-model="showArea" round position="bottom" class="checkArea">
      <van-area :area-list="areaList" item-height="45rem" visible-item-count="8"
                :columns-placeholder="['请选择', '请选择', '请选择']" title="请选择所在地区"
                @confirm="checkArea" @cancel="showArea=false"/>
    </van-popup>
  </div>
  <!-- 开发环境版本,包含了有帮助的命令行警告 -->
  <script src="../plugins/vue/vue.js"></script>
  <!-- 引入组件库 -->
  <script src="../plugins/vant/vant.min.js"></script>
  <script src="../plugins/vant/area-data.js"></script>
  <!-- 引入axios -->
  <script src="../plugins/axios/axios.min.js"></script>
  <script src="../js/request.js"></script>
  <script src="../js/common.js"></script>
  <script src="../api/address.js"></script>
  <script>
    new Vue({
      el: "#address_edit",
      data() {
        return {
          title: '新增收货地址',
          form: {
            consignee: '',
            sex: '1',
            phone: '',
            detail: '',
            tag: '',
            isDefault: false
          },
          area: '',
          areaInfo: [],
          tagList: ['家', '公司', '学校'],
          showArea: false,
          areaList
        }
      },
      created() {
        this.initData()
      },
      methods:{
        initData() {
          this.id = getUrlParam('id')
          if(this.id) {
            this.title = '编辑收货地址'
            getAddressByIdApi(this.id).then(res => {
              const data = res.data
              this.form = data
              this.form.sex = data.sex.toString()
              this.form.isDefault = !!data.isDefault  // !!可以转换为boolean类型
              this.area = data.provinceName + '/' + data.cityName + '/' + data.districtName
            }).catch(error => {
              this.$notify({type: 'danger', message: error.message})
            })
          }
        },

        // 保存地址
        async saveAddress() {
          const form = this.form
          if (!form.consignee) {
            this.$toast('请填写收货人姓名')
            return
          }
          if (!form.phone) {
            this.$toast('请填写手机号')
            return
          }
          const phoneReg = /^1(3|4|5|6|7|8)\d{9}$/
          if (!phoneReg.test(form.phone)) {
            this.$toast('请填写正确的手机号')
            return
          }
          if (!this.area) {
            this.$toast('请选择地区')
            return
          }
          if (!form.detail) {
            this.$toast('请填写详细地址')
            return
          }
          this.$toast.loading({
            duration: 0,
            forbidClick: true,
            message: '保存中'
          })
          const params = {
            ...form,
            isDefault: form.isDefault ? 1 : 0
          }
          if (this.areaInfo.length > 0) {
            params.provinceCode = this.areaInfo[0].code
            params.provinceName = this.areaInfo[0].name
            params.cityCode = this.areaInfo[1].code
            params.cityName = this.areaInfo[1].name
            params.districtCode = this.areaInfo[2].code
            params.districtName = this.areaInfo[2].name
          }
          const res = this.id ? await editAddressApi(params) : await addAddressApi(params)
          if (res.code === 20000) {
            this.$toast('保存成功')
            this.goBack()
          } else {
            this.$toast(res.message)
          }
        },

        // 删除地址
        deleteAddress() {
          this.$dialog.confirm({
            title: '提示',
            message: '是否删除地址？',
            confirmButtonText: '删除'
          }).then(() => {
            this.$toast.loading({
              duration: 0,
              forbidClick: true,
              message: '删除中'
            })
            deleteAddressApi(this.id).then(res => {
              this.$toast('删除成功')
              this.goBack()
            }).catch(error => {
              this.$toast(error.message)
            })
          }).catch(() => {})
        },

        // 选中地区
        checkArea(valueList) {
          for (const value of valueList) {
            if (!value || !value.name || !value.code) {
              this.$toast('请选择地区')
              return
            }
          }
          this.area = valueList.map(value => value.name).join('/')
          this.areaInfo = valueList
          this.showArea = false
        },

        // 选中标签
        checkTag(tag) {
          this.form.tag = this.form.tag === tag ? '' : tag
        },

        goBack() {
          window.requestAnimationFrame(() => {
            history.back()
          })
        }
      }
    })
    </script>
</body>
</html>
